package alit.generator.bl.populator;

import alit.generator.bl.generator.Context;

import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * User: Alexander Litvinenko
 * Date: 11/19/11
 * Time: 2:02 PM
 */
public class VarcharPopulatorKit extends PopulatorKit {

    public static final String TYPE = "varchar";

    public static class FromAllRangePopulator implements IPopulator {

        private static final String alphabet = "abcdefghijklmnopqrstuvwxyz";

        public static String getId() {
            return "fromAllRange";
        }

        public String populate(Context context) {
            String result = "";
            for (int i = 0; i < getRandom().nextInt(20) + 1; i++) {
                result += alphabet.charAt(getRandom().nextInt(alphabet.length()));
            }
            return "'" + result + "'";
        }
    }

    public static class CalculatedFieldPopulator implements IPopulator {

        private String expression;
        public static final Pattern PATTERN = Pattern.compile("\\{[^@][^\\}]+\\}");

        public CalculatedFieldPopulator(String expression) {
            this.expression = expression;
        }

        public static String getId() {
            return "calculatedField";
        }

        public String populate(Context context) {
            return "'" + processIds(expression, context)
                    .replace("{@now}", new Date().toString())
                    .replace("{@row}", String.valueOf(context.getCurrentRow()))
                    .replace("{@name}", context.getCurrentColumnName()) + "'";
        }

        private String processIds(String expression, Context context) {
            Matcher matcher = PATTERN.matcher(expression);
            String temp = expression;
            while (matcher.find()) {
                String id = temp.substring(matcher.start() + 1, matcher.end() - 1);
                String currentValue = context.getCurrentValueByColumnName(id);
                if (currentValue == null) {
                    throw new PopulatorException("Column column hasn't populate yet!");
                }
                temp = matcher.replaceFirst(currentValue);
                matcher.reset(temp);
            }
            return temp;
        }
    }

    @Override
    public String getSqlDialect() {
        return DialectUtils.MS_SQL_SERVER;
    }

    @Override
    public String getTypeName() {
        return TYPE;
    }

}